<?php

namespace Admin\Controller;

use Think\Controller;
use Think\Page;

/**
 * 控制器基类
 * Class CommonController
 * @package Admin\Controller
 */
class CommonController extends Controller
{
    protected $pageSize = 20;

    /**
     * @inheritdoc
     */
    public function __construct()
    {
        parent::__construct();
        $admin_id = session('admin_id');
        if (!$admin_id) redirect(U('/Admin/Login'));
        // if(strtolower(CONTROLLER_NAME) == 'index')
        // return true;
        /*$where = array(
            'module_name' => MODULE_NAME,
            'controller_name' => CONTROLLER_NAME,
            'action_name' => ACTION_NAME,
            'admin_id' => $admin_id
        );
        $res = $this->_checkPrivilege($where);
        if ($res['status'] < 0) {
            if (IS_AJAX) {
                $this->ajaxReturn($res);
                exit;
            } else {
                $this->error($res['info']);
            }
        }*/

        get_global_config();

        $this->pageSize = 20;
    }

    /**
     * 检测权限
     * @param $where
     * @return array
     */
    private function _checkPrivilege($where)
    {
        $has = D('Privilege')->hasPrivilege($where);
        if ($has < 1) {
            return array('status' => -1, 'info' => '无访问权限!');
        }
        return array('status' => 1, 'info' => '允许防问!');
    }


    /**
     * 通用分页列表数据集获取方法
     *
     *  可以通过url参数传递where条件,例如:  index.html?name=asdfasdfasdfddds
     *  可以通过url空值排序字段和方式,例如: index.html?_field=id&_order=asc
     *  可以通过url参数r指定每页数据条数,例如: index.html?r=5
     *
     * @param string|\Think\Model $model 模型名或模型实例
     * @param array $where where查询条件(优先级: $where>$_REQUEST>模型设定)
     * @param array|string $order 排序条件,传入null时使用sql默认排序或模型属性(优先级最高);
     *                              请求参数中如果指定了_order和_field则据此排序(优先级第二);
     *                              否则使用$order参数(如果$order参数,且模型也没有设定过order,则取主键降序);
     *
     * @param boolean $field 单表模型用不到该参数,要用在多表join时为field()方法指定参数
     *
     * @return array|false 数据集
     */
    protected function lists($model, $where = array(), $order = '', $field = true)
    {
        $options = array();
        $REQUEST = (array)I('request.');
        if (is_string($model)) {
            $model = D($model);
        }

        $OPT = new \ReflectionProperty($model, 'options');
        $OPT->setAccessible(true);

        $pk = $model->getPk();
        if ($order === null) {
            //order置空
        } else if (isset($REQUEST['_order']) && isset($REQUEST['_field']) && in_array(strtolower($REQUEST['_order']), array('desc', 'asc'))) {
            $options['order'] = '`' . $REQUEST['_field'] . '` ' . $REQUEST['_order'];
        } elseif ($order === '' && empty($options['order']) && !empty($pk)) {
            $options['order'] = $pk . ' desc';
        } elseif ($order) {
            $options['order'] = $order;
        }
        unset($REQUEST['_order'], $REQUEST['_field']);

        if (empty($where)) {
            $where = array('state' => array('eq', 0));
        }
        if (!empty($where)) {
            $options['where'] = $where;
        }
        $options = array_merge((array)$OPT->getValue($model), $options);
        $total = $model->where($options['where'])->count();

        if (isset($REQUEST['r'])) {
            $listRows = (int)$REQUEST['r'];
        } else {
            $listRows = C('LIST_ROWS') > 0 ? C('LIST_ROWS') : 20;
        }

        // 修正分页搜索时页码过大问题
        $p = I('p', 1);
        $tempTotalPage = intval($total / $listRows) + 1;
        if ($p >= $tempTotalPage) {
            $p = $tempTotalPage;
        }
        $_GET['p'] = $p;

        $page = new Page($total, $listRows, $REQUEST);
        $page->setConfig('first', '首页');
        $page->setConfig('prev', '上一页');
        $page->setConfig('next', '下一页');
        $page->setConfig('last', '尾页');
        if ($total > $listRows) {
            $page->setConfig('theme', '%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% 第 ' . $p . ' 页/共 %TOTAL_PAGE% 页 ( ' . $listRows . ' 条/页 共 %TOTAL_ROW% 条)');
        }
        foreach ($where as $key => $val) {
            $page->parameter[$key] = urlencode($val);
        }
        $p = $page->show();
        $this->assign('page', $p ? $p : '');
        $this->assign('count', $total);
        $options['limit'] = $page->firstRow . ',' . $page->listRows;

        $model->setProperty('options', $options);

        return $model->field($field)->select();
    }

}